<template>
  <div class="profile-container">
    <div class="page-header">
      <a-button type="primary" shape="circle" @click="router.back()" class="back-button">
        <template #icon><ArrowLeftOutlined /></template>
      </a-button>
      <h1 class="page-title">个人中心</h1>
    </div>
    <a-row :gutter="24">
      <!-- 左侧：用户信息表单 -->
      <a-col :span="16">
        <a-card title="基本信息" class="profile-card">
          <a-form :model="user" layout="vertical">
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="姓名">
                  <a-input v-model:value="user.userName" placeholder="请输入姓名" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="ID">
                  <a-input v-model:value="user.id" disabled />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="邮箱">
                  <a-input v-model:value="user.email" placeholder="请输入邮箱" />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="手机号">
                  <a-input v-model:value="user.phone" placeholder="请输入手机号" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="性别">
                  <a-radio-group v-model:value="user.gender">
                    <a-radio :value="0">男</a-radio>
                    <a-radio :value="1">女</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="学校">
                  <a-input v-model:value="user.school" placeholder="请输入学校" />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item label="个人简介">
              <a-textarea
                v-model:value="user.userProfile"
                placeholder="介绍一下自己吧"
                :rows="4"
              ></a-textarea>
            </a-form-item>
            <a-form-item label="注册时间">
              <a-input v-model:value="user.createTime" disabled />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" :loading="loading" @click="saveProfile">保存修改</a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>

      <!-- 右侧：头像和统计 -->
      <a-col :span="8">
        <a-card class="profile-card text-center">
          <a-avatar :size="120" :src="user.userAvatar || '/src/assets/default.jpg'" class="avatar">
            <template #icon><UserOutlined /></template>
          </a-avatar>
          <div class="avatar-actions">
            <a-button type="primary" @click="showAvatarModal" class="avatar-btn"
              >生成AI头像</a-button
            >
          </div>
          <h2 class="nickname">{{ user.userName || '未设置姓名' }}</h2>
          <p class="user-school">{{ user.school || '未设置学校' }}</p>
          <a-divider />
          <div class="stats-container">
            <div class="stat-item">
              <div class="stat-value">{{ userStats.resumeCount }}</div>
              <div class="stat-label">简历筛选</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.writtenCount }}</div>
              <div class="stat-label">笔试测试</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.techCount }}</div>
              <div class="stat-label">技术面试</div>
            </div>
          </div>
          <a-divider />
          <div class="stats-container">
            <div class="stat-item">
              <div class="stat-value">{{ userStats.hrCount }}</div>
              <div class="stat-label">HR面试</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ userStats.fullCount }}</div>
              <div class="stat-label">全流程面试</div>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- AI头像生成弹窗 -->
    <a-modal
      v-model:visible="avatarModalVisible"
      title="生成AI头像"
      @ok="confirmAvatar"
      :confirmLoading="avatarLoading"
    >
      <div class="avatar-modal-content">
        <a-form-item label="头像描述">
          <a-textarea
            v-model:value="avatarDescription"
            placeholder="请输入头像的描述，例如：'微笑的程序员'"
            :rows="3"
          />
        </a-form-item>
        <a-button
          type="primary"
          :loading="generatingAvatar"
          @click="generateAvatar"
          class="generate-btn"
        >
          生成头像
        </a-button>
        <div v-if="previewAvatar" class="avatar-preview">
          <img :src="previewAvatar" alt="AI生成的头像" class="preview-img" />
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { UserOutlined, ArrowLeftOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserstore'
import { generateAvatarUsingGet, updateMyUserUsingPost } from '@/api/userController'

const router = useRouter()
const loading = ref(false)
const userStore = useLoginUserStore()

// 用户基本信息 - 使用 onMounted 中获取的真实数据
const user = reactive({
  userAvatar: '',
  userName: '加载中...',
  id: '加载中...',
  email: '',
  phone: '',
  gender: 0,
  school: '',
  userProfile: '',
  createTime: '',
})

// 用户统计数据
const userStats = reactive({
  resumeCount: 0,
  writtenCount: 0,
  techCount: 0,
  hrCount: 0,
  fullCount: 0,
})

// 学习进度
const learningProgress = reactive({
  interview: 0,
  written: 0,
  resume: 0,
})

// AI头像生成相关
const avatarModalVisible = ref(false)
const avatarDescription = ref('')
const previewAvatar = ref('')
const generatingAvatar = ref(false)
const avatarLoading = ref(false)

/**
 * 从仓库中获取用户信息
 */
const fetchUserData = async () => {
  const userInfo = userStore.loginUser
  if (userInfo) {
    // 将用户信息填充到表单中
    user.userAvatar = userInfo.userAvatar || ''
    user.userName = userInfo.userName || ''
    user.id = userInfo.id || ''
    user.email = userInfo.email || ''
    user.phone = userInfo.phone || ''
    user.gender = userInfo.gender !== undefined ? userInfo.gender : 0
    user.school = userInfo.school || ''
    user.userProfile = userInfo.userProfile || ''
    user.createTime = userInfo.createTime || ''

    // 这里应该从后端获取用户的面试统计数据
    // 暂时使用随机数模拟
    userStats.resumeCount = Math.floor(Math.random() * 5)
    userStats.writtenCount = Math.floor(Math.random() * 8)
    userStats.techCount = Math.floor(Math.random() * 6)
    userStats.hrCount = Math.floor(Math.random() * 4)
    userStats.fullCount = Math.floor(Math.random() * 3)
  }
}

const saveProfile = async () => {
  loading.value = true
  // 调用接口保存修改信息
  const data = await updateMyUserUsingPost({
    userName: user.userName,
    phone: user.phone,
    email: user.email,
    gender: user.gender,
    school: user.school,
    userProfile: user.userProfile,
  })
  if (data.code === 0){
    message.success('个人信息已更新')
  }else{
    message.error('个人信息更新失败')
  }
  loading.value = false
}

/**
 * 显示头像生成弹窗
 */
const showAvatarModal = () => {
  avatarModalVisible.value = true
  avatarDescription.value = ''
  previewAvatar.value = ''
}

/**
 * AI生成用户头像
 */
const generateAvatar = async () => {
  if (!avatarDescription.value.trim()) {
    message.warning('请输入头像描述')
    return
  }
  // 调用接口生成头像
  await generateUserAvatarByAI()
}

/**
 * 确认使用生成的头像
 */
const confirmAvatar = async () => {
  if (!previewAvatar.value) {
    message.warning('请先生成头像')
    return
  }

  // 显示正在替换头像的加载动画
  avatarLoading.value = true
  // 调用接口更换用户头像
  const data = await updateMyUserUsingPost({
    userAvatar: previewAvatar.value,
  })
  if (data.code === 0){
    //更新仓库中用户信息
    await userStore.fetchLoginUser()
    //重新获取仓库中用户信息
    await fetchUserData()

    message.success('头像已更新')
  }else {
    message.error('头像更新失败')
  }
  // 关闭头像替换的加载动画
  avatarLoading.value = false
  // 关闭头像生成弹窗
  avatarModalVisible.value = false
}

/**
 * AI生成用户头像底层函数（由你来实现具体调用）
 */
const generateUserAvatarByAI = async () => {

  // 显示生成头像加载动画
  generatingAvatar.value = true
  try {
    const data = await generateAvatarUsingGet({ description: avatarDescription.value })
    if (data.code === 0) {
      message.success('头像生成成功')
      previewAvatar.value = data.data as any
      console.log(data.data)
    } else {
      message.error('生成头像失败')
    }
  } catch (error) {
    message.error('生成头像失败，请稍后再试')
    console.error(error)
  } finally {
    //关闭生成头像加载动画
    generatingAvatar.value = false
  }
}

onMounted(() => {
  fetchUserData()
})
</script>

<style scoped>
.profile-container {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.back-button {
  margin-right: 16px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #1f2d3d;
}

.profile-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  margin-bottom: 24px;
}

.text-center {
  text-align: center;
}

.avatar {
  margin-bottom: 16px;
  border: 4px solid #fff;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.avatar-actions {
  margin-bottom: 16px;
}

.avatar-btn {
  margin: 0 4px;
}

.nickname {
  font-size: 20px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.user-school {
  font-size: 14px;
  color: #909399;
  margin-bottom: 16px;
}

.stats-container {
  display: flex;
  justify-content: space-around;
  margin: 16px 0;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-value {
  font-size: 22px;
  font-weight: 600;
  color: #303133;
}

.stat-label {
  font-size: 13px;
  color: #606266;
  margin-top: 4px;
}

.progress-container {
  text-align: left;
}

.progress-item {
  margin-bottom: 16px;
}

.progress-item:last-child {
  margin-bottom: 0;
}

.progress-item span {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #606266;
}

/* AI头像相关样式 */
.avatar-modal-content {
  text-align: center;
}

.generate-btn {
  margin-bottom: 16px;
}

.avatar-preview {
  margin-top: 16px;
  display: flex;
  justify-content: center;
}

.preview-img {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #f0f0f0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>
